import {
  FlatList,
  useWindowDimensions,
  RefreshControl,
  TouchableOpacity,
} from 'react-native';
import React, {useState, useEffect} from 'react';
import {TabView, TabBar, SceneMap} from 'react-native-tab-view';
import PopularItem from '../../components/PopularItem.jsx';
import Refresh from '../../components/Refresh.jsx';
import NavigationBar from '../../components/NavigationBar.jsx';
import Icon from '@react-native-vector-icons/fontawesome';
import {useNavigation} from '@react-navigation/native';
import isEmpty from 'lodash/isEmpty';
import {useSelector, useDispatch} from 'react-redux';
import {changePopularData, fetchPopular} from '../../store/popular.js';

function PageItem({index, indexKey, tabs}) {
  const popular = useSelector(state => state.popular);
  const dispatch = useDispatch();

  useEffect(() => {
    if (
      tabs[index].key === indexKey &&
      isEmpty(popular.popularData[indexKey])
    ) {
      const type = tabs[index].key;
      dispatch(fetchPopular({type, key: indexKey}));
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [index]);

  const changeFavorite = item => {
    dispatch(changePopularData({item, key: indexKey}));
  };

  const renderItem = ({item}) => {
    return <PopularItem item={item} changeFavorite={changeFavorite} />;
  };

  const handleRefresh = () => {
    const type = tabs[index].key;
    dispatch(fetchPopular({type, key: indexKey, refresh: true}));
  };

  const handleEndReached = () => {
    console.log('22221');
  };

  return (
    <>
      {!isEmpty(popular.popularData[indexKey]) ? (
        <FlatList
          refreshControl={
            <RefreshControl
              colors={['tomato']}
              refreshing={popular.refresh}
              onRefresh={handleRefresh}
            />
          }
          onEndReached={handleEndReached}
          onEndReachedThreshold={0.5}
          ListFooterComponent={<Refresh content="正在加载更多" />}
          data={popular.popularData[indexKey]}
          keyExtractor={item => item.id}
          renderItem={renderItem}
        />
      ) : (
        <Refresh fullScreen />
      )}
    </>
  );
}

export default function PopularPage() {
  const layout = useWindowDimensions();
  const [index, setIndex] = useState(0);
  const navigation = useNavigation();

  const tabs = ['Java', 'Android', 'iOS', 'React', 'React Native', 'PHP'].map(
    v => ({key: v, title: v}),
  );

  const renderScene = SceneMap(
    tabs.reduce((res, item) => {
      res[item.key] = () => (
        <PageItem index={index} indexKey={item.key} tabs={tabs} />
      );
      return res;
    }, {}),
  );

  return (
    <>
      <NavigationBar
        title={'最热'}
        rightButton={
          <TouchableOpacity
            onPress={() => {
              navigation.navigate('Search');
            }}>
            <Icon name="search" color="#fff" size={20} />
          </TouchableOpacity>
        }
      />
      <TabView
        renderTabBar={props => <TabBar {...props} scrollEnabled />}
        navigationState={{index, routes: tabs}}
        renderScene={renderScene}
        onIndexChange={setIndex}
        initialLayout={{width: layout.width}}
      />
    </>
  );
}
